<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\JsonResponse;

class PostController extends Controller
{
    /**
     * 获取文章详情
     *
     * @param Post $post
     * @return JsonResponse
     */
    public function show(Post $post): JsonResponse
    {
        try {
            // 检查文章是否已发布
            if ($post->status !== 'published' || 
                !$post->published_at || 
                $post->published_at > now()) {
                return response()->json([
                    'success' => false,
                    'message' => '文章不存在或未发布',
                ], 404);
            }

            // 增加浏览量
            $post->increment('views');

            // 加载关联数据
            $post->load(['user', 'category', 'tags']);

            $postData = [
                'id' => $post->id,
                'title' => $post->title,
                'slug' => $post->slug,
                'content' => $post->content,
                'excerpt' => $post->excerpt,
                'published_at' => $post->published_at,
                'views' => $post->views,
                'user' => $post->user ? [
                    'id' => $post->user->id,
                    'name' => $post->user->name,
                ] : null,
                'category' => $post->category ? [
                    'id' => $post->category->id,
                    'name' => $post->category->name,
                    'slug' => $post->category->slug,
                ] : null,
                'tags' => $post->tags->map(function ($tag) {
                    return [
                        'id' => $tag->id,
                        'name' => $tag->name,
                        'slug' => $tag->slug,
                    ];
                }),
            ];

            return response()->json([
                'success' => true,
                'post' => $postData,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取文章详情失败',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}